<template>
  <div class="works">
    <div class="wkHead">

      <el-row>
        <el-col style="margin-right: 20px;" :span="5">
          <el-form-item label="作业名称" prop="workName">
            <el-input @keyup.enter="onSearch" placeholder="请输入作业名称" v-model.trim="classRuleForm.workName" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item>
            <el-button :icon="Search" type="primary" @click="onSearch">
              搜索
            </el-button>
            <el-button :icon="Refresh" @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>


    </div>


    <div v-if="!counterStore().excellentClass" class="wkButton">
      <el-button type="primary" plain icon="Plus" @click='addWorkFn'>新增作业</el-button>
      <el-button @click="exportWorks" type="warning" plain ><span style="margin-right: 6px;" class="iconfont icon-topsales"></span> 导出</el-button>
    </div>

    <div class="wkTable">
      <div v-if="worksArr.length>0">
        <el-table :data="worksArr" id="tableData" style="width: 100%;overflow-x:auto; height: 70vh" class="studentTable" >
          <el-table-column width="350px" prop="name" label="作业名称">
            <template #default="scope">
              <div style="display: flex; align-items: center;">
              <el-tag v-if="scope.row.t" effect="plain" round type="success">考试</el-tag>
              <el-tag v-else effect="plain" round type="primary">作业</el-tag>
               <span class="wkName" @click='viewWorkDet(scope.row.id)' style="cursor: pointer; margin-left: 5px;"> {{ giveEllipsisStr(scope.row.name, 18) }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column width="120px" align="center" prop="status" label="状态">
            <template #default="scope">
              <el-tag :type='giveTagState(scope.row.status_name)'>{{ scope.row.status_name }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column width="150px" align="center" prop="nick_name" label="创建者">
            <template #default="scope">
              {{ scope.row.nick_name }}
            </template>
          </el-table-column>


          <el-table-column width="150px" align="center" prop="release_time" label="开始时间">
            <template #default="scope">
              {{ scope.row.release_time }}
            </template>
          </el-table-column>

          <el-table-column width="200px" align="center" prop="end_time" label="结束时间">
            <template #default="scope">
              {{ scope.row.end_time }}
            </template>
          </el-table-column>

          <el-table-column  width="150px" align="center" label="批阅数/作业量">
            <template #default="scope">
              <span style="font-size: 30px;
              color: #555;">{{ scope.row.review_count ? scope.row.review_count : 0 }}</span> /
              <span style="font-size: 14px;
              color: #999;"> {{ scope.row.sub_count
 ? scope.row.sub_count
 : 0 }}</span>
            </template>
          </el-table-column>

          <el-table-column width="80px" align="center" prop="count" label="班级人数">
            <template #default="scope">
              <b style="font-size: 18px;">{{ scope.row.count ? scope.row.count : 0 }}</b>人
            </template>
          </el-table-column>

          <el-table-column min-width="200px" align="center" prop="final_score" label="操作">
            <template #default="scope">
              <ul>
                <ul>
                  <li v-if="!counterStore().excellentClass"  class='review-btn' @click='goReview(scope.row.id, scope.row.count)'>查阅</li>
                  <li class='revise-btn'>
                    <!-- <span v-if="scope.row.status_name=='未发布'||scope.row.status_name=='未知'" @click='goEditWork(scope.row.id)'>修改</span>
                    <span v-else @click='viewWorkDet(scope.row.id)'>详情</span> -->
                    <span @click='goEditWork(scope.row.id)'>修改</span>
                  </li>

              

                  <li class='del-btn' v-if='!scope.row.readOnly'>
                    <el-popconfirm v-if="!counterStore().excellentClass"  title='是否确认删除?' confirm-button-text='确认删除' @confirm='delRowWork(scope.row.id)'>
                      <template #reference>删除</template>
                    </el-popconfirm>
                  </li>
                </ul>
              </ul>
            </template>


          </el-table-column>
        </el-table>
      </div>

      <div style="display: flex; justify-content: center; align-items: center; height: 60vh"   v-else>
      <el-empty :image-size="200"   description='暂无作业,请新增！！！' />
      </div>
    </div>

    <!-- 新增作业对话框 -->
    <div class="addWorksDialog">
    <el-dialog top='5vh' v-model='dialogVisible' :title="rowData ? '修改作业' : '新建作业'" width='1000px' append-to-body
      :close-on-click-modal='false' destroy-on-close @close='closeWorkDia'>
      <AddWork :rowData='rowData' v-model:dialogVisible='dialogVisible' @resetData='getWorkList' />
    </el-dialog>
  </div>


  <el-dialog top='5vh' v-model='workdetdialogVisible' title="作业详情" width='1000px' append-to-body
      :close-on-click-modal='false' destroy-on-close>
      <workdetDialog  :rowData='rowData'/>
  </el-dialog>
  </div>
</template>
<script setup>
import { ref } from "vue";
import { Search, Refresh } from "@element-plus/icons-vue";
import { giveEllipsisStr, giveTagState, parseTime } from '@/utils/common';
import AddWork from './AddWork';
import workdetDialog from './workdet-dialog.vue';
import { worklist, delWorkRow, getRowWork } from '@/api/banke/zuoye'
import { _export_tworks } from "@/utils/excel_util";
import counterStore from "@/store/modules/counter";
const loading = ref(false)
const pageTotal = ref(0);
const router = useRouter()
const { proxy } = getCurrentInstance()
const dialogVisible = ref(false);
const workdetdialogVisible=ref(false)
import { ElLoading, ElMessage } from 'element-plus';
// 修改一条作业的数据
const rowData = ref(null);

const classRuleForm = ref({
  workName: "",
})

// 作业列表测试数据
const worksArr = ref([])

//点击新增作业按钮
const addWorkFn = () => {
  rowData.value = null
  dialogVisible.value = true;
};
// 删除一条作业
const delRowWork = (id) => {

  delWorkRow(id).then(res => {
    if (!res) {
      ElMessage.success('删除成功');
      getWorkList()

    } else {
      ElMessage.error(res.response.data);
    }

  })
}

// 修改作业
const goEditWork = (id) => {
  const loadingInstance = ElLoading.service();
  console.log(id);
  // 获取一条作业详情
  getRowWork(id).then(res => {
    console.log(res);


    // 处理图像回显问题
const processString = (str) => {
  // 处理 img 标签的 src 替换为 alt 中的 url
  const processedImgStr = str.replace(/<img[^>]*alt="\[file_id:[^,]*,url: ([^"]*)"[^>]*>/g, (match, url) => {
    return match.replace(/src="[^"]*"/, `src="${url.replace(/\]/g, '')}"`);
  });

  // 处理 video 标签中的 source 标签的 src 替换为 poster 中的 url
  const processedVideoStr = processedImgStr.replace(/<video[^>]*poster="\[file_id:[^,]*,url: ([^"]*)"[^>]*>.*?<source[^>]*src="[^"]*"[^>]*>/g, (match, url) => {
    return match.replace(/<source[^>]*src="[^"]*"/, `<source src="${url.replace(/\]/g, '')}"`);
  });


  return processedVideoStr;
};

res.content = processString(res.content);

    // // 去除多余的符号
    res.content=res.content.replace(/>" data-href="?" style="?"\//g, '');
    rowData.value = res;
    loadingInstance.close();
    dialogVisible.value = true;
  });
}
//点击查阅作业
const goReview = (id, total_count) => {
  console.log(id);
  router.push({ path: '/designclass/referwork', query: { activeNum: 5, operateId: id, total_count } });
};
// 重置表单
const resetForm = () => {
  classRuleForm.value.workName = ''
  getWorkList()
}
//获取作业列表
const getWorkList = (keyname = '') => {
  loading.value = true
  let data = {
    page_size: 200,
    page_num: 1,
    name: keyname,
    bk_id: counterStore().bkItem.id
  }
  worklist(data).then(res => {
    console.log(res.list);

    if (res.list) {
      worksArr.value = res.list
      worksArr.value.forEach(e=>{
        e.release_time=parseTime(e.release_time,"{m}月{d}日{h}时")   
        e.end_time=parseTime(e.end_time,"{m}月{d}日{h}时")
        
      })
      pageTotal.value = res.total_count;
    } else {
      ElMessage.error('操作有误请重新刷新');
    }
  }).finally(() => {
    loading.value = false
  })
};


const closeWorkDia = () => {


}

// 导出作业
const exportWorks=()=>{

 
  worksArr.value.forEach(e=>{
    if(e.release_time==null){
      e.release_time=''
    }
  })

  
  _export_tworks(worksArr.value, "作业列表.xlsx");

}

// 搜索作业
const onSearch = () => {
  getWorkList(classRuleForm.value.workName)
}

// 点击详情查看作业详情
const viewWorkDet=(id)=>{
  const loadingInstance = ElLoading.service();
  // 获取一条作业详情
  getRowWork(id).then(res => { 

// 处理图像回显问题
const processString = (str) => {
  // 处理 img 标签的 src 替换为 alt 中的 url
  const processedImgStr = str.replace(/<img[^>]*alt="\[file_id:[^,]*,url: ([^"]*)"[^>]*>/g, (match, url) => {
    return match.replace(/src="[^"]*"/, `src="${url.replace(/\]/g, '')}"`);
  });

  // 处理 video 标签中的 source 标签的 src 替换为 poster 中的 url
  const processedVideoStr = processedImgStr.replace(/<video[^>]*poster="\[file_id:[^,]*,url: ([^"]*)"[^>]*>.*?<source[^>]*src="[^"]*"[^>]*>/g, (match, url) => {
    return match.replace(/<source[^>]*src="[^"]*"/, `<source src="${url.replace(/\]/g, '')}"`);
  });

  return processedVideoStr;
};

res.content = processString(res.content);



    
    rowData.value = res;
    loadingInstance.close();
    workdetdialogVisible.value = true;
  });

}






getWorkList()
</script>

<style lang="scss" scoped>

.addWorksDialog{
   z-index: -1;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: auto;
}
.works {
  min-width: 1200px;
}

.wkTable {
  margin-top: 30px;
.wkName{
  cursor: pointer;
  margin-left: 5px;
  &:hover{
    color: #4395FF;
  }
}
  .top,
  .row {
    display: flex;
    align-items: center;
  }

  .top {
    display: flex;
    align-items: center;
    background: #F5F7FA;
    color: #888;
    line-height: 45px;
    font-size: 14px;
    display: flex;

  }



  .name {
    width: 20%;
    padding-left: 18px;
    text-align: left;
  }

  .status {
    width: 10%;
  }

  .author {
    width: 8%;
  }

  .posttime,
  .deadline {
    width: 14%;
  }

  .done-all {
    width: 12%;
  }

  .count {
    width: 8%;
    font-size: 13px;

    b {
      font-size: 18px;
    }
  }

  .operate {
    width: 10%;
    text-align: left;
  }



  .row {
    line-height: 55px;
    font-size: 16px;
    color: #555;


    .name {
      font-size: 16px;
      color: #555555;
    }

    .status {
      color: #FF5733;
    }

    .status.not-started {
      color: #FF5733;
    }

    .status.in-progress {
      color: #4395FF;
    }

    .status.has-ended {
      color: #86DFB2;
    }

    .posttime,
    .deadline {
      color: #888;
      font-size: 14px;
    }



    .operate {
      font-size: 14px;
      color: #888;

      
    }


  }

  .row:hover {
    background: #E7F1FF;

    .operate {
      display: block;
    }
  }


}

.done-all {


  span {
    font-size: 30px;
    color: #555555;
  }
}


ul {
        width: 100%;
        display: flex;
        justify-content: center;

        li {
       
          margin: 0 10px;
          color: #888;
          cursor: pointer;
          text-align: center;
        
          transition: .3s;
          
        }

        li.review-btn {
          color: #4395FF;
        }


        li.del-btn:hover {
          color: #FF5733;
        }
      }

     .wkButton{
      margin-top: 20px;
     }
</style>


<style>
.works .el-table__row {
      height: 60px; 
    }

.el-scrollbar .el-scrollbar__wrap{
  overflow: visible;
}
</style>